#!/usr/bin/python2.7

# Copyright 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
import os
import webapp2

from google.appengine.api import channel
from google.appengine.ext import db
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext.webapp import template
from django.utils import simplejson as json


class Endpoint(db.Model):
  connected = db.BooleanProperty()


class MainPage(webapp2.RequestHandler):
  def get(self):
    endpoint = Endpoint(connected=False)
    endpoint.put()
    token = channel.create_channel(str(endpoint.key()))
    path = os.path.join(os.path.dirname(__file__), 'template.html')
    self.response.out.write(template.render(path, {'token': token}))


class IncomingMailPage(InboundMailHandler):
  def receive(self, mail_message):
    query = Endpoint.all()
    query.filter('connected =', True)
    
    body_to_inject = ''
    for type, body in mail_message.bodies():
      body_to_inject = '<b>' + type + '</b>: ' + body.decode() + '<br>';
      break

    message = {'numClients': 0,
               'numSenders': 0,
               'From': mail_message.sender,
               'To': mail_message.to,
               'Subject': mail_message.subject,
               'Bodies': body_to_inject}
    for endpoint in query:
      channel.send_message(str(endpoint.key()), json.dumps(message))


class ChannelConnectedHandler(webapp2.RequestHandler):
  def post(self):
    endpoint = Endpoint.get(db.Key(self.request.get('from')))
    endpoint.connected = True
    endpoint.put()


class ChannelDisconnectedHandler(webapp2.RequestHandler):
  def post(self):
    endpoint = Endpoint.get(db.Key(self.request.get('from')))
    endpoint.connected = False
    endpoint.put()


app = webapp2.WSGIApplication([('/', MainPage),
                               ('/_ah/channel/connected/', ChannelConnectedHandler),
                               ('/_ah/channel/disconnected/', ChannelDisconnectedHandler),
                               (IncomingMailPage.mapping())], debug=True)
